package com.jvm123

import groovy.sql.GroovyRowResult
import groovy.sql.Sql

/**
 * @author yawn
 */

def initGoods(int num) {

    Sql sql = Sql.newInstance(Constant.URL, Constant.USER, Constant.PWD, Constant.DRIVER)

    println sql.execute("delete from goods")
    for (i in 0..num) {
        sql.execute("insert into goods value(UUID_SHORT())")
    }
    sql.close()
}

initGoods(99)


def initOrder(int num) {

    Sql sql = Sql.newInstance(Constant.URL, Constant.USER, Constant.PWD, Constant.DRIVER)

    sql.execute("delete from order_goods")
    for (i in 0..num) {
        String randomQuerySql = "SELECT id FROM goods WHERE id >= ((SELECT MAX(id) FROM goods)-(SELECT MIN(id) FROM goods)) * RAND() + (SELECT MIN(id) FROM goods) LIMIT ?"
        int orderSize = (Math.random() * 15).intValue() + 3
        List<GroovyRowResult> randomList = sql.rows(randomQuerySql, [orderSize])
        String orderId = UUID.randomUUID().toString().replace("-", "")
        for (GroovyRowResult goods : randomList) {
            String goodsId = goods.get("id")
            sql.execute("insert into order_goods value(?, ?)", [orderId, goodsId])
        }
    }
    sql.close()
}

initOrder(49999)


def initRelation() {

    Sql sql = Sql.newInstance(Constant.URL, Constant.USER, Constant.PWD, Constant.DRIVER)

    sql.execute("delete from goods_relation")
    List<GroovyRowResult> goodsList = sql.rows("SELECT id FROM goods")
    for (int i = 0; i < goodsList.size(); i++) {
        String goods1Id = goodsList.get(i).get("id")
        for (int j = i + 1; j < goodsList.size(); j++) {
            String goods2Id = goodsList.get(j).get("id")
            sql.execute("insert into goods_relation value(?, ?, 0)", [goods1Id, goods2Id])
        }
        println i
    }
    sql.close()
}

initRelation()